﻿//-----------------------------------------------------------------------
// <copyright file="HtmlRemoval.cs" company="Microsoft Corporation">
//     Copyright Microsoft Corporation. All Rights Reserved. This code released under the terms of the Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.) This is sample code only, do not use in production environments.
// </copyright>
//-----------------------------------------------------------------------

namespace VisualStudioOnlineOData.Utilities
{
    using System.Text;
    using System.Text.RegularExpressions;

    /// <summary>
    /// Methods to remove HTML from strings.
    /// </summary>
    public static class HtmlRemoval
    {
        private static Regex htmlBreak = new Regex("<[Bb][Rr][^>]*>");
        private static Regex htmlParagraph = new Regex("<[Pp][^>/]*>");

        /// <summary>
        /// Remove HTML tags from string using char array.
        /// </summary>
        public static string StripTagsCharArray(string source)
        {
            var initialCleanup = htmlBreak.Replace(source, "\n");
            initialCleanup = htmlParagraph.Replace(initialCleanup, "\n");
            var builder = new StringBuilder(initialCleanup.Length);
            bool inside = false;
            for (int i = 0; i < initialCleanup.Length; i++)
            {
                var character = initialCleanup[i];
                if (character == '<' && !inside)
                {
                    inside = true;
                    continue;
                }

                if (character == '>' && inside)
                {
                    inside = false;
                    continue;
                }

                if (!inside)
                {
                    builder.Append(character);
                }
            }

            return builder.ToString();
        }
    }
}